package com.test.clyq.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.test.clyq.entity.Users;
import com.test.clyq.entity.UsersLog;
import com.test.clyq.service.UserService;
import com.test.clyq.service.UsersLogService;
import com.test.json.JsonUtil;
import com.test.util.DateUtils;
import com.test.util.FormatExceptionStack;
import com.test.util.ItemUtil;
import com.test.util.Pagination;
import com.test.util.SessionUtil;
import com.test.webapp.action.BaseAction;

/**
 * UserAction. <br>
 * 用户管理.
 * <p>
 * Copyright: Copyright (c) 2010-4-18 下午04:51:40
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * Author: liuxl@c-platform.com
 * <p>
 * Version: 1.0
 * <p>
 */
public class UserAction extends BaseAction {

	/**
	 * 添加用户
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward addUser(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException {
		this.log.info("添加用户start");
		try {
			this.log.debug("添加用户成功");
			this.log.info("添加用户end");
			return mapping.findForward("addUser");
		}
		catch (Exception e) {
			this.log.error("添加用户:失败 " + FormatExceptionStack.formatException(e));
			request.setAttribute("HtmlError", "对不起，系统服务器忙，请您稍候再试.");
			return null;
		}

	}

	/**
	 * 验证手机验证码
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return pingBack
	 * @throws IOException
	 */
	public ActionForward checkMobileRand(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		String mobileRand = request.getParameter("mobileRand");
		String sRand = (String) request.getSession().getAttribute("mobileRand");
		UsersLogService usersLogService = (UsersLogService) getBean("usersLogService");
		try {
			if (!mobileRand.equals(sRand)) {
				print(response, "<script>alert('验证码不正确!');location.href='/mobileRand.jsp';</script>", null, null);
			} else {
				Users user = (Users) request.getAttribute("currUser");
				SessionUtil.setSession(request, user);

				UsersLog userLog = new UsersLog();

				userLog.setOperateTime(System.currentTimeMillis());
				userLog.setUsedTime(1000l);

				userLog.setUsersId(user.getId());
				userLog.setUsersLoginName(user.getUsersLoginName());

				userLog.setOperateType(Long.valueOf(ItemUtil.LOGINON));
				userLog.setOperateDataType(5l);
				userLog.setOperateStatus(1l);
				userLog.setOperateTableKey(user.getId());

				userLog.setBeforeOperateData(null);
				userLog.setAfterOperateData(user.getUsersLoginName() + " 在  "
				        + DateUtils.longToDateString(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss" + " 登录系统!") + "登录IP为："
				        + request.getRemoteAddr());

				usersLogService.addUsersLog(userLog);
				response.sendRedirect("/index.jsp");
			}
			return null;
		}
		catch (Exception e) {
			this.log.error("login:失败 " + FormatExceptionStack.formatException(e));
			request.setAttribute("HtmlError", "对不起，系统服务器忙，请您稍候再试.");
			return mapping.findForward("error");
		}
	}

	/**
	 * 检查权限
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward checkP(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException {
		this.log.info("检查权限start");

		try {
			Users user = SessionUtil.getUserFromSession(request);
			String str = null;
			if (user != null && !user.getIsUsersAdmin().equals(1l)) {
				str = "-1";
			} else if (user != null && user.getIsUsersAdmin().equals(1l)) {
				str = "1";
			} else {
				str = "-1";
			}
			print(response, str, null, null);
		}
		catch (Exception e) {
			this.log.error("修改栏目:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;

	}

	/**
	 * 删除用户
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward delUser(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException {
		this.log.info("删除用户start");
		String uId = request.getParameter("uId");
		UserService userService = (UserService) getBean("userService");
		Users user = SessionUtil.getUserFromSession(request);
		try {
			boolean bl = userService.delUsersById(Long.valueOf(uId), user);
			StringBuilder sb = new StringBuilder();
			sb.append("{");
			if (bl) {
				sb.append("success:true");
			} else {
				sb.append("success:false");
			}
			sb.append("}");
			String dd = sb.toString();
			print(response, dd, null, null);
			this.log.debug("删除用户成功");
			this.log.info("删除用户end");
		}
		catch (Exception e) {
			this.log.error("删除用户:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;

	}

	/**
	 * 修改用户
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward editUser(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("修改用户start");
		UserService userService = (UserService) getBean("userService");
		String uId = request.getParameter("uId");
		try {
			Users user = userService.getUsersById(Long.valueOf(uId));
			this.log.debug("修改用户成功");
			this.log.info("修改用户end");
			String fragStr = "{results:[{";
			fragStr += user.toJSON();
			fragStr += "}]}";
			print(response, fragStr, null, null);
		}
		catch (Exception e) {
			this.log.error("修改用户:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;

	}

	/**
	 * login
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return pingBack
	 * @throws IOException
	 */
	public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String pwd = request.getParameter("pwd");
		String uName = request.getParameter("name");
		String rand = request.getParameter("checkCode");
		String sRand = (String) request.getSession().getAttribute("rand");
		UsersLogService usersLogService = (UsersLogService) getBean("usersLogService");
		StringBuilder sb = new StringBuilder();
		sb.append("{success:true,");
		if (!rand.equals(sRand)) {
			sb.append("message:'noRand'");
			sb.append("}");
			print(response, sb.toString(), null, null);
			return null;
		}
		UserService userService = (UserService) getBean("userService");
		try {
			pwd = DigestUtils.md5Hex(pwd);
			Users user = userService.getUsersByNameAndPwd(uName, pwd);
			if (user != null) {
				SessionUtil.setSession(request, user);
				UsersLog userLog = new UsersLog();
				userLog.setOperateTime(Long.valueOf(System.currentTimeMillis()));
				userLog.setUsedTime(Long.valueOf(1000L));
				userLog.setUsersId(user.getId());
				userLog.setUsersLoginName(user.getUsersLoginName());
				userLog.setOperateType(Long.valueOf(3L));
				userLog.setOperateDataType(Long.valueOf(5L));
				userLog.setOperateStatus(Long.valueOf(1L));
				userLog.setOperateTableKey(user.getId());
				userLog.setBeforeOperateData(null);
				userLog.setAfterOperateData((new StringBuilder(String.valueOf(user.getUsersLoginName()))).append(" 在  ")
				        .append(DateUtils.longToDateString(Long.valueOf(System.currentTimeMillis()), "yyyy-MM-dd HH:mm:ss 登录系统!")).append("登录IP为：")
				        .append(request.getRemoteAddr()).toString());
				usersLogService.addUsersLog(userLog);
				sb.append("message:'logon'");
				sb.append("}");
				print(response, sb.toString(), null, null);
			} else {
				sb.append("message:'logoError'");
				sb.append("}");
				print(response, sb.toString(), null, null);
			}
		}
		catch (Exception e) {
			log.error((new StringBuilder("login:失败 ")).append(FormatExceptionStack.formatException(e)).toString());
			sb.append("message:'logoError'");
			sb.append("}");
			print(response, sb.toString(), null, null);
		}
		return null;
	}

	/**
	 * loginOut
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return pingBack
	 * @throws IOException
	 */
	public ActionForward loginOut(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		Users user = SessionUtil.getUserFromSession(request);
		UsersLogService usersLogService = (UsersLogService) getBean("usersLogService");
		try {
			UsersLog userLog = new UsersLog();
			userLog.setOperateTime(System.currentTimeMillis());
			userLog.setUsedTime(1000l);
			userLog.setUsersId(user.getId());
			userLog.setUsersLoginName(user.getUsersLoginName());
			userLog.setOperateType(Long.valueOf(ItemUtil.LOGINOUT));
			userLog.setOperateDataType(5l);
			userLog.setOperateStatus(1l);
			userLog.setOperateTableKey(user.getId());
			userLog.setBeforeOperateData(null);
			userLog.setAfterOperateData(user.getUsersLoginName() + " 在  "
			        + DateUtils.longToDateString(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss" + " 退出系统!"));
			usersLogService.addUsersLog(userLog);
			request.getSession().setAttribute("user", null);
			request.getSession().setAttribute("webSiteName", null);
			SessionUtil.destroySession(request);
			print(response, true);
			return null;
		}
		catch (Exception e) {
			this.log.error("login:失败 " + FormatExceptionStack.formatException(e));
			request.setAttribute("HtmlError", "对不起，系统服务器忙，请您稍候再试.");
			return mapping.findForward("error");
		}
	}

	/**
	 * 保存用户
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward saveUser(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("保存用户start");
		Users user = new Users();
		String uName = request.getParameter("user_name");
		String fullName = request.getParameter("user_full_name");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		String desc = request.getParameter("desc");
		String phone = request.getParameter("phone");
		String mobile = request.getParameter("mobile");
		String address = request.getParameter("address");
		String isUserAdmin = request.getParameter("isUsersAdmin");
		String website = request.getParameter("usersWebsite");
		UserService userService = (UserService) getBean("userService");
		try {
			user.setUsersAddress(address);
			user.setUsersDesc(desc);
			user.setUsersLoginName(uName);
			user.setUsersEmail(email);
			user.setUsersMobile(mobile);
			user.setUsersPhone(phone);
			user.setUsersPassword(DigestUtils.md5Hex(password));
			user.setIsUsersAdmin(Long.valueOf(isUserAdmin));
			user.setUsersFullName(fullName);
			// user.setUsersWebsite(Integer.valueOf(website));
			userService.saveOrUpdate(user);
			this.log.debug("保存用户成功");
			this.log.info("保存用户end");
			print(response, true);
		}
		catch (Exception e) {
			this.log.error("保存用户:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;
	}

	/**
	 * 更新用户
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ActionForward updateUser(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("更新用户start");
		String uName = request.getParameter("usersLoginName");
		String fullName = request.getParameter("usersFullName");
		String email = request.getParameter("usersEmail");
		String desc = request.getParameter("usersDesc");
		String phone = request.getParameter("usersPhone");
		String mobile = request.getParameter("usersMobile");
		String address = request.getParameter("usersAddress");
		String password = request.getParameter("password");
		String uId = request.getParameter("usersId");
		UserService userService = (UserService) getBean("userService");
		try {
			Users user = userService.getUsersById(Long.valueOf(uId));
			user.setUsersAddress(address);
			user.setUsersDesc(desc);
			user.setUsersLoginName(uName);
			user.setUsersEmail(email);
			user.setUsersMobile(mobile);
			user.setUsersPhone(phone);
			// user.setIsUsersAdmin(Long.valueOf(0));
			user.setUsersFullName(fullName);
			if ((password != null) && (!"".equals(password))) {
				user.setUsersPassword(DigestUtils.md5Hex(password));
			}
			userService.saveOrUpdate(user);
			this.log.debug("更新用户成功");
			this.log.info("更新用户end");
			print(response, true);
		}
		catch (Exception e) {
			this.log.error("保存用户:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;
	}

	/**
	 * 获得用户列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return 用户列表
	 * @throws IOException
	 */
	public ActionForward userList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("获得用户列表start");
		UserService userService = (UserService) getBean("userService");
		try {
			Pagination pagination = new Pagination(1, 100);// 设置分页参数（页码和每页显示记录条数）
			List<Users> list = null;
			list = userService.userList(pagination); // 获取用户列表
			String jsonStr = JsonUtil.getJsonStr(list, null, -1);
			this.log.debug("获得用户列表成功");
			this.log.info("获得用户列表end");
			print(response, jsonStr, null, null);
		}
		catch (Exception e) {
			this.log.error("获得用户:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;
	}

	/**
	 * 获得用户列表(选择框)
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return 用户列表
	 * @throws IOException
	 */
	public ActionForward userSelectList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
	        throws IOException {
		this.log.info("获得用户列表start");
		UserService userService = (UserService) getBean("userService");
		try {
			Pagination pagination = new Pagination(1, 1000);// 设置分页参数（页码和每页显示记录条数）
			List<Users> list = userService.userList(pagination); // 获取用户列表
			String jsonStr = JsonUtil.getJsonStr(list, null, -1);
			this.log.debug("获得用户列表成功");
			this.log.info("获得用户列表end");
			print(response, jsonStr, null, null);
		}
		catch (Exception e) {
			this.log.error("获得用户:失败 " + FormatExceptionStack.formatException(e));
			print(response, false);
		}
		return null;
	}
}
